package com.kuang.security;

import com.kuang.util.ResponseUtil;
import com.kuang.util.ResultModel;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 退出处理类
 */
public class TokenLogoutHandler implements LogoutHandler {

    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;
    
    public TokenLogoutHandler(TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }

    /**
     * request 封装HTTP请求消息
     * response 封装HTTP响应消息
     * authentication 封装用户的验证请求信息
     * */
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        // 1. 从请求头中获得前端携带的token
        String token = request.getHeader("token");
        // 防止空指针异常,判断token是否为空
        if (!StringUtils.isNullOrEmpty(token)){
            // 2. 使用jwt解析token
            String username = tokenManager.getUsernameFromToken(token);
            // 3. 删除redis中的数据
            redisTemplate.delete(username);
        }

        // 将字符串转为json格式并返回给前端
        ResponseUtil.out(response, ResultModel.success("注销成功"));
    }
}
